package siruna.WE.core.model.FunctionalBlocks;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.apache.http.MethodNotSupportedException;

import siruna.WE.core.model.FunctionalBlock;

public class ImageLoaderImpl extends FunctionalBlock {

	@Override
	public byte[] toByteArray() {
		URL aURL;
		BufferedInputStream bis = null;
		try {
			aURL = new URL(getAttributes().get("url"));

			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			/* Buffered is always good for a performance plus. */
			bis = new BufferedInputStream(is);
			return inputStreamToBytes(bis);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	private byte[] inputStreamToBytes(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
		byte[] buffer = new byte[1024];
		int len;

		while ((len = in.read(buffer)) >= 0)
			out.write(buffer, 0, len);

		in.close();
		out.close();
		return out.toByteArray();
	}

	@Override
	public List toList() throws MethodNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String toHTML() {

		String s = "var "+getId()+" = new ImageLoader('"
				+ getAttributes().get("url") + "');";
		return s;

	}
}
